//
//  CommunityViewController.swift
//  FM
//
//  Created by x on 2017/8/23.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class CommunityViewController: UIViewController {
    
    /// 保存正在显示的控制器
    weak var showingController:UIViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    /// 初始化
    func setupUI() -> Void {
        view.backgroundColor = UIColor.white
        navigationItem.title = "社区"
        
        //1.添加子控件
        segmentView.choiseDelegate = self
        view.addSubview(segmentView)
        
        //2.添加子控制器
        addChildViewController(essenceController)
        addChildViewController(newestController)
        
        //2.1默认初始化显示第一个控制器
        showingController = childViewControllers.first
        
        //2.2把显示的控制器的view添加上去
        showingController?.view.frame = CGRect(x: 0, y: segmentView.bounds.height, width: view.bounds.width, height: view.bounds.height-49-segmentView.bounds.height)
        view.addSubview((showingController?.view)!)
    }
    
    //MARK: -- 懒加载
    
    fileprivate lazy var segmentView:SegmentView = SegmentView(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: 40))
    
    private lazy var essenceController:EssenceViewController = EssenceViewController()
    
    private lazy var newestController:NewestViewController = NewestViewController()
}

extension CommunityViewController:SegmentViewDelegate {
    
    func btuWillClick(index: Int) {
        print(#function)
        //1.首先移除正在显示的控制器的View
        showingController?.view.removeFromSuperview()
        
        //2.获得将要显示的控制器
        showingController = childViewControllers[index-1];
        
        //3.把控制器添加到父控制器上
        showingController?.view.frame = CGRect(x: 0, y: segmentView.bounds.height, width: view.bounds.width, height: view.bounds.height-49-segmentView.bounds.height)
        view.addSubview((showingController?.view)!)
    }
}
